package com.mall.b2c.controller;

import static com.mall.b2c.Constants.PRINCIPAL_SESSION_NAME;
import static com.mall.common.bean.WebErrors.ERROR_ATTR_NAME;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;

import com.mall.b2c.Constants;
import com.mall.b2c.hessian.StoreHessian;
import com.mall.common.ipseek.IPSeeker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSONObject;
import com.mall.b2c.bean.MemberBean;
import com.mall.b2c.bean.Principal;
import com.mall.b2c.hessian.MemberHessian;
import com.mall.common.bean.Message;
import com.mall.common.bean.WebErrors;
import com.mall.common.exception.NoticeException;
import com.mall.common.exception.ResourceNotFoundException;
import com.mall.common.util.AppContext;

public class BaseController {
	@Resource private Validator validator;
	@Resource protected MemberHessian memberHessian;
	@Resource protected StoreHessian storeHessian;
	@Resource protected IPSeeker ipSeeker;
	protected static final String FRONT_ERROR_PAGE = "/error.jhtml";
	protected static final Message errorMessage = Message.error("mall.message.error", new Object[0]);
	protected static final Message successMessage = Message.success("mall.message.success", new Object[0]);
	protected Log log = LogFactory.getLog(getClass());

	protected void addActionError(HttpServletRequest request, String message){
		WebErrors errors = (WebErrors)request.getAttribute(ERROR_ATTR_NAME);
		if(errors == null){
			errors = WebErrors.create();
			request.setAttribute(ERROR_ATTR_NAME, errors);
		}
		errors.addErrorString(message);
	}
	/**
	 * 发送utf8的请求
	 * @param url
	 * @return
	 * @throws IOException
	 */
    protected String renderHtmlUTF8(String url, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");  
		response.setDateHeader("Expires", 0);
		response.getWriter().write(url);
		response.getWriter().flush();
		return null;
	}
    
	/**
	 * 清除缓存
	 */
	protected void clearCache(HttpServletResponse response){
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store");  
		response.setDateHeader("Expires", 0);
	}
	
	@ExceptionHandler
	public void exceptionHandler(Exception ex,
			HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException{
		if(AppContext.isAjax(request)){
			if(ex.getClass() == NoticeException.class){
				this.addActionError(request, ex.getMessage());
			}else{
				log.error("System Error", ex);
				this.addActionError(request, "系统错误!");
			}
			WebErrors errors = (WebErrors)request.getAttribute(ERROR_ATTR_NAME);
			errors.showErrorAjax(response);
		}else{
			if(ex.getClass() == NoticeException.class){
				this.addActionError(request, ex.getMessage());
				request.getRequestDispatcher(FRONT_ERROR_PAGE).forward(request, response);
			}else if(ex.getClass() == ResourceNotFoundException.class){
				response.sendRedirect("/common/resource_not_found.jhtml");
			}else{
				log.error("System Error", ex);
				this.addActionError(request, "系统错误");
				request.getRequestDispatcher(FRONT_ERROR_PAGE).forward(request, response);
			}
		}
	}

	/**
	 * 获取当前会员的帐号和id
	 * @return
	 */
	protected Principal getPrincipal(){
		Object obj = AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
		if(obj != null){
			return (Principal) obj;
		}
		return null;
	}

	/**
	 * 获取当前会员的id
	 * @return
	 */
	protected Long getMemberId(){
		Principal principal = getPrincipal();
		if(principal != null){
			return principal.getId();
		}
		return null;
	}
	
	/**
	 * 获取当前会员信息
	 * @return
	 */
	protected MemberBean getMember(){
		Long id = getMemberId();
		if(id == null){
			return null;
		}
		return jsonToObj(memberHessian.getMemberInfo(id, null), MemberBean.class);
	}


	protected Long getCurrStoreId(){
		/*//自定义门店
		StoreBean store = (StoreBean)AppContext.getSessionAttr(Constants.CURR_STORE_SESSION_KEY);
		if(store == null ){
			IPLocation ipLocation = ipSeeker.getIPLocation(AppContext.getRemoteIp());//"125.110.94.53"
			String cityName = "";
			if(ipLocation != null){
				cityName = ipLocation.getCity();
			}
			store = jsonToObj(storeHession.getDefaultStore(cityName), StoreBean.class);
		}
		AppContext.setSessionAttr(Constants.CURR_STORE_SESSION_KEY, store);
		return store.getId();*/
		Cookie cookie = AppContext.getCookie(Constants.CURR_STORE_COOKIE_KEY);//选中门店
		Pattern pattern = Pattern.compile("\\d+");
		Long storeId = 1L;
		if(cookie != null && pattern.matcher(cookie.getValue()).matches()){//有选中城市
			storeId = Long.parseLong(cookie.getValue());
		}
		return storeId;
	}

	/**
	 * 跳转到404页面
	 * @param response
	 * @return
	 * @throws IOException
	 */
	protected String redirectTo404(HttpServletResponse response) throws IOException{
		response.sendRedirect("/html/error_page_404.html");
		return null;
	}

	/**
	 * 将json转换成对象
	 * @param json json值
	 * @param clazz 转换的类型
	 * @return
	 */
	protected <T> T jsonToObj(String json, Class<T> clazz){
		return JSONObject.parseObject(json, clazz);
	}
	
	/**
	 * 将json转换成list
	 * @param json json值
	 * @param clazz 转换的类型
	 * @return
	 */
	protected <T> List<T> jsonToList(String json, Class<T> clazz){
		return JSONObject.parseArray(json, clazz);
	}
}
